package com.yx.cloud.map.layer;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.text.TextPaint;
import android.text.TextUtils;

import com.aaa.lib.map.MapView;
import com.aaa.lib.map.area.CircleArea;
import com.iot.common.utils.LogUtils;
import com.iot.product.sweeper.bean.AreaInfo;
import com.iot.product.sweeper.bean.CleanParam;
import com.iot.product.sweeper.bean.MapInfo;
import com.iot.product.sweeper.bean.Room;
import com.iot.sweeper.AppContext;
import com.yx.cloud.R;
import com.yx.cloud.map.YXMapView;

import org.json.JSONObject;

//TODO 随地图缩放 , 否则做多地图缩略图时标签显示太大
public class YXRoomTagLayer extends YXAreaLayer<CircleArea> {

    private static final String TAG = "YXRoomTagLayer";
    private static final float MIN_TAG_PADDING_VERTICAL = 6;
    private static final float MIN_TAG_PADDING_HORIZONTAL = 3;

    protected Bitmap water_low;
    protected Bitmap water_mid;
    protected Bitmap water_high;
    protected Bitmap water_no;
    protected Bitmap suction_quiet;
    protected Bitmap suction_auto;
    protected Bitmap suction_strong;
    protected Bitmap suction_max;
    protected Bitmap suction_no;
    protected Bitmap clean_once;
    protected Bitmap clean_twice;
    private boolean clickTag = false;
    private TextPaint textPaint;
    private Paint bgPaint;
    private Paint bgCustomPaint;
    private RectF bgRect;
    private RectF customRect;
    private float paddingX = MIN_TAG_PADDING_HORIZONTAL;
    private float paddingY = MIN_TAG_PADDING_VERTICAL;
    private float density = 1;
    private String showName = "   ";

    private float lastPosX;
    private float lastPosY;
    private boolean isMove = false;

    public YXRoomTagLayer(MapView mapView) {
        super(mapView);
        setLayerLevel(6);
        area = new CircleArea();
        areaInfo = new Room();
        bgRect = new RectF();
        customRect = new RectF();

        density = mapView.getResources().getDisplayMetrics().density;
        textPaint = new TextPaint();
        textPaint.setAntiAlias(true);
        textPaint.setTextSize(5);
        textPaint.setAntiAlias(true);

        bgPaint = new Paint();
        bgPaint.setStyle(Paint.Style.FILL);
//        bgPaint.setShadowLayer(2, 5, 5, mResource.getColor(R.color.shadow_54));

        bgCustomPaint = new Paint();
        bgCustomPaint.setStyle(Paint.Style.FILL);
        bgCustomPaint.setColor(mResource.getColor(R.color.water_background));

        water_low = BitmapFactory.decodeResource(mapView.getContext().getResources(), R.mipmap.checked_water_low_custom);
        water_mid = BitmapFactory.decodeResource(mapView.getContext().getResources(), R.mipmap.checked_water_middle_custom);
        water_high = BitmapFactory.decodeResource(mapView.getContext().getResources(), R.mipmap.checked_water_tall_custom);
        water_no = BitmapFactory.decodeResource(mapView.getContext().getResources(), R.mipmap.checked_no_suction_custom);
        suction_quiet = BitmapFactory.decodeResource(mapView.getContext().getResources(), R.mipmap.checked_quiet_suction_custom);
        suction_auto = BitmapFactory.decodeResource(mapView.getContext().getResources(), R.mipmap.checked_standard_suction_custom);
        suction_strong = BitmapFactory.decodeResource(mapView.getContext().getResources(), R.mipmap.checked_powerful_suction_custom);
        suction_max = BitmapFactory.decodeResource(mapView.getContext().getResources(), R.mipmap.checked_super_suction_custom);
        suction_no = water_no;
        clean_once = BitmapFactory.decodeResource(mapView.getContext().getResources(), R.mipmap.checked_clean_once_custom);
        clean_twice = BitmapFactory.decodeResource(mapView.getContext().getResources(), R.mipmap.checked_clean_twice_custom);

    }

    @Override
    protected boolean onTouchDown(float x, float y) {
        boolean selectable = ((YXMapView) mMapView).canSelectRoom();
        if (!selectable) {
            return false;
        }
        //判断点击位置
        getTransformedPoint(mMapView.getTransform(), x, y);//如果是随地图缩放的方式绘制  这一句就不用写

        int id = getTouchPointRoomId(x, y);

        isMove = false;
        lastPosX = x;
        lastPosY = y;

        if (visible && (bgRect.contains(tmpPoint[0], tmpPoint[1]) || id == areaInfo.getId())) {
            clickTag = true;
        } else {
            //不在点击范围内 下一位
            clickTag = false;
        }

        //return  clickTag; 这里不能返回clickTag 因为一旦返回 时间就交给了此tag 后续就不能拖动地图了
        return false;
    }

    private int getTouchPointRoomId(float x, float y) {
        MapInfo mapBean = ((YXMapView) mMapView).getMap().getMap();
        int index = ((int) y) * mapBean.width + (int) x;
        if (index >= 0 && mapBean.mapData != null && index < mapBean.mapData.length) {
            return mapBean.mapData[index];
        }
        return MapInfo.TYPE_NONE;
    }

    @Override
    protected boolean onTouchMove(float x, float y) {
        boolean selectable = ((YXMapView) mMapView).canSelectRoom();
        if (!selectable) {
            return false;
        }

        float translateX = Math.abs(x - lastPosX);
        float translateY = Math.abs(y - lastPosY);
        if (translateX + translateY > 5) {
            //如果移动距离大于3 那么说明是在移动 不改变选中状态
            isMove = true;
        }
        return false;
    }

    @Override
    protected boolean onTouchUp(float x, float y) {
        boolean selectable = ((YXMapView) mMapView).canSelectRoom();
        boolean canMultiSelectRoom = ((YXMapView) mMapView).canMultiSelectRoom();
        if (!selectable) {
            return false;
        }

        if (isMove) {
            //移动了 不再选中
            return false;
        }

        //判断点击位置
        if (clickTag) {
            //如果是单选 那么不让它取消选中
            if (!canMultiSelectRoom && isSelected) {
                ((YXMapView) mMapView).handleRoomSelect(this, true);
            } else {
                isSelected = !isSelected;
                ((YXMapView) mMapView).handleRoomSelect(this, isSelected);
            }
            //阻止其他tag被选中
            return true;
        }
        return false;
    }


    @Override
    public void draw(Canvas canvas) {
        if (!visible) {
            return;
        }

        drawFrame(canvas);
//        drawFrame1(canvas);
    }

    private void drawFrame(Canvas canvas) {
        boolean selectable = ((YXMapView) mMapView).canSelectRoom();
        boolean multiSelectable = ((YXMapView) mMapView).canMultiSelectRoom();
        boolean showOrder = ((YXMapView) mMapView).isShowRoomOrder();
        boolean showWater = ((YXMapView) mMapView).isShowWater();
        boolean showCleanTimes = ((YXMapView) mMapView).isShowCleanTimes();
        boolean showCustom = ((YXMapView) mMapView).isShowCustom();

        textPaint.setTextSize(density * 11);
        //重新设置矩形 和文本宽高
        Paint.FontMetrics fontMetrics = textPaint.getFontMetrics();
        float textWidth = textPaint.measureText(showName);   //测量文本长度
        float textHeight = fontMetrics.descent - fontMetrics.ascent;    //计算文本高度

        getTransformedPoint(mMapView.getTransform(), area.x, area.y);
        float centerX = tmpPoint[0];
        float centerY = tmpPoint[1];
        //矩形大小：  height= textHeight+2*padding    width = textWidth+ 2* textHeight/2 (左右两个半圆内不写字) +padding*2
        float left = centerX - (textWidth / 2 + paddingX + textHeight / 2);
        float top = centerY - (textHeight / 2 + paddingY);
        float right = centerX + (textWidth / 2 + paddingX + textHeight / 2);
        float bottom = centerY + (textHeight / 2 + paddingY);

        bgRect.set(left, top, right, bottom);

        //float radius = (textHeight + padding) / 2;
        float radius = (bottom - top) / 2;
        if (selectable && isSelected) {
            //如果选中了 并且显示序号 那么就绘制序号
            if (showOrder) {
                float orderTextWidth = textPaint.measureText(order + "");
                textPaint.setColor(mResource.getColor(R.color.textview_color2));
                bgPaint.setColor(mResource.getColor(R.color.white));
                canvas.drawCircle(centerX, bgRect.top - paddingY - radius, radius, bgPaint);
                canvas.drawText(order + "", (bgRect.right + bgRect.left) / 2 - orderTextWidth / 2, bgRect.top - paddingY - radius + textHeight / 2 - fontMetrics.bottom, textPaint);
            }
            //如果可以选中  并且选中了 那么就绘制蓝底白字
            textPaint.setColor(mResource.getColor(R.color.white));
            bgPaint.setColor(mResource.getColor(R.color.button_color2));
        } else {
            //如果不可选中 或者没有选中 那么就绘制白底灰字
            textPaint.setColor(mResource.getColor(R.color.textview_color2));
            bgPaint.setColor(mResource.getColor(R.color.white));
        }

        //绘制圆角矩形， 圆角半径为高度的一半 即一个椭圆的条条
        canvas.drawRoundRect(bgRect, radius, radius, bgPaint);        //TODO 画圆角矩形内存泄露是我完全想不到的。。。 啥情况。。。

        canvas.drawText(showName, centerX - textWidth / 2, centerY + textHeight / 2 - fontMetrics.bottom, textPaint);

        //定制模式  画吸力水量图标
        Bitmap suction_status = getSuctionStatus(((Room) areaInfo).getSuction());
        Bitmap water_status = getWaterStatus(((Room) areaInfo).getHumidity());
        Bitmap clean_times = getCleanTimes(((Room) areaInfo).getCleanTimes());

        //计算定制icon个数 来设置背景大小
        int itemCount = 0;
        if (suction_status != null) {
            itemCount++;
        }
        if (showWater && water_status != null) {
            itemCount++;
        }
        if (showCleanTimes && clean_times != null) {
            itemCount++;
        }
        if (showCustom && itemCount != 0) {
            float iconWidth = suction_quiet.getWidth();
            float iconHeight = suction_quiet.getHeight();
            //圆角半径 = icon高度/2 + padding
            radius = MIN_TAG_PADDING_VERTICAL + iconHeight / 2;

            //间距个数 三个图标 就有两个间距
            int paddingCount = (itemCount == 0) ? 0 : itemCount - 1;
            float customRectWidth = iconWidth * itemCount + paddingX * paddingCount + radius;
            customRect.left = (left + right) / 2 - customRectWidth / 2;
            customRect.right = (left + right) / 2 + customRectWidth / 2;
            customRect.top = bottom + paddingY;
            customRect.bottom = bottom + paddingY + iconHeight + paddingY * 2;

            //绘制圆角矩形， 圆角半径为高度的一半 即一个椭圆的条条
            canvas.drawRoundRect(customRect, radius, radius, bgCustomPaint);

            if (suction_status != null) {
                canvas.drawBitmap(suction_status, customRect.left + radius / 2, customRect.top + paddingY, null);//第二个参数是x半径，第三个参数是y半径
            }
            if (showWater && water_status != null) {
                if (suction_status == null) {
                    //如果没有吸力图标  画在第一个位置
                    canvas.drawBitmap(water_status, customRect.left + radius / 2, customRect.top + paddingY, null);//第二个参数是x半径，第三个参数是y半径
                } else {
                    //如果有吸力图标 画在第二位
                    canvas.drawBitmap(water_status, customRect.left + radius / 2 + paddingX + iconWidth, customRect.top + paddingY, null);//第二个参数是x半径，第三个参数是y半径
                }
            }
            if (showCleanTimes && clean_times != null) {
                canvas.drawBitmap(clean_times, customRect.left + radius / 2 + (paddingX + iconWidth) * (itemCount - 1), customRect.top + paddingY, null);//第二个参数是x半径，第三个参数是y半径
            }

        }
    }

    private Bitmap getWaterStatus(int waterLevel) {
        Bitmap waterStatus = null;
        switch (waterLevel) {
            case 1:
                waterStatus = water_low;
                break;
            case 2:
                waterStatus = water_mid;
                break;
            case 3:
                waterStatus = water_high;
                break;
            case 0:
                waterStatus = water_no;
                break;
        }
        return waterStatus;
    }

    private Bitmap getSuctionStatus(int suctionLevel) {
        Bitmap suctionStatus = null;
        switch (suctionLevel) {
            case 1:
                suctionStatus = suction_quiet;
                break;
            case 2:
                suctionStatus = suction_auto;
                break;
            case 3:
                suctionStatus = suction_strong;
                break;
            case 4:
                suctionStatus = suction_max;
                break;
            case 0:
                suctionStatus = suction_no;
                break;
        }
        return suctionStatus;
    }

    private Bitmap getCleanTimes(int times) {
        Bitmap cleanTimes = null;
        switch (times) {
            case 2:
                cleanTimes = clean_twice;
                break;
            case 1:
                cleanTimes = clean_once;
        }
        return cleanTimes;
    }

    @Override
    public void initAreaLayer(AreaInfo areaInfo) {
        LogUtils.i(areaInfo.toString());
        Room room = (Room) areaInfo;
        area.setCenter(room.getCenter());

        String alias = getSpecifiedName(room.getName());
        room.setAlias(alias);
        setAreaInfo(room);

        String name = TextUtils.isEmpty(alias) ? areaInfo.getName() : alias;
        if (name.length() > 15) {
            name = name.substring(0, 15) + "...";
        }
        showName = name;

    }

    /*
     "yxroom_name_1" = "客厅";
     "yxroom_name_2" = "主卧";
     "yxroom_name_3" = "次卧";
     "yxroom_name_4" = "衣帽间";
     "yxroom_name_5" = "玄关";
     "yxroom_name_6" = "阳台";
     "yxroom_name_7" = "厨房";
     "yxroom_name_8" = "书房";
     "yxroom_name_9" = "餐厅";
     "yxroom_name_10" = "儿童房";
     "yxroom_name_11" = "卫生间";
     */
    public String getSpecifiedName(String name) {
        String specifiedName = name;
        JSONObject productConfig = AppContext.getConfig();
/*        if (X5.get().getConfig().productName.equals(productConfig.productName)) {
            //X5不使用别名
            return specifiedName;
        }*/

        if ("yxroom_name_1".equals(name)) {
            specifiedName = mResource.getString(R.string.MM_MasterBedroom);
        } else if ("yxroom_name_2".equals(name)) {
            specifiedName = mResource.getString(R.string.MM_LivingRoom);
        } else if ("yxroom_name_3".equals(name)) {
            specifiedName = mResource.getString(R.string.MM_SecondBedroom);
        } else if ("yxroom_name_4".equals(name)) {
            specifiedName = mResource.getString(R.string.MM_Cloakroom);
        } else if ("yxroom_name_5".equals(name)) {
            specifiedName = mResource.getString(R.string.MM_Vestibule);
        } else if ("yxroom_name_6".equals(name)) {
            specifiedName = mResource.getString(R.string.MM_Balcony);
        } else if ("yxroom_name_7".equals(name)) {
            specifiedName = mResource.getString(R.string.MM_Kitchen);
        } else if ("yxroom_name_8".equals(name)) {
            specifiedName = mResource.getString(R.string.MM_StudyRoom);
        } else if ("yxroom_name_9".equals(name)) {
            specifiedName = mResource.getString(R.string.MM_DiningRoom);
        } else if ("yxroom_name_10".equals(name)) {
            specifiedName = mResource.getString(R.string.MM_KidBedroom);
        } else if ("yxroom_name_11".equals(name)) {
            specifiedName = mResource.getString(R.string.MM_Bathroom);
        }
        return specifiedName;
    }

    @Override
    public Room getAreaInfo() {
        return (Room) areaInfo;
    }

    public void setCleanParam(CleanParam cleanParam) {
        Room room = (Room) areaInfo;
        room.setCleanTimes(cleanParam.cleanTimes);
        room.setSuction(cleanParam.suction);
        room.setHumidity(cleanParam.humidity);
        room.setSweepType(cleanParam.cleanType);
    }

    @Override
    public boolean isEditable() {
        //父类中有使用此判断 , 如果为false则不可点击
        return true;
    }

}
